/**
 * Copyright (c) 2014-2016 www.nryuncang.com. All Rights Reserved.
 */
package com.topisv.tms.web.orderexport;

import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springside.modules.web.Servlets;

import com.topisv.tms.entity.AreaGroup;
import com.topisv.tms.entity.Customers;
import com.topisv.tms.entity.EdiOrder;
import com.topisv.tms.entity.EdiOrderItem;
import com.topisv.tms.entity.JSONParam;
import com.topisv.tms.entity.QueryParamHolder;
import com.topisv.tms.entity.lpn.LPN;
import com.topisv.tms.entity.work.WorkOrder;
import com.topisv.tms.service.AreaGroupService;
import com.topisv.tms.service.CustomersService;
import com.topisv.tms.service.LogisticsCompanyService;
import com.topisv.tms.service.account.ShiroDbRealm.ShiroUser;
import com.topisv.tms.service.orderexport.OrderExportService;
import com.topisv.tms.tools.DataTablesUtils;
import com.topisv.tms.tools.ExcelUtils;
import com.topisv.tms.utils.DateUtils;
import com.topisv.tms.utils.enums.StatusEnums;
import com.topisv.tms.web.base.BaseDataTableController;
import com.topisv.tms.web.report.FirstPageController;

import net.sf.json.JSONObject;

/**
 * 
 *
 * @author <a href=mailto:zhangweize@nryuncang.com>zhangweize</a>
 * @version 1.0.0
 */
@Controller
@RequestMapping(value = "/v2/orderExport")
public class OrderExportController extends BaseDataTableController {
	private static final Logger logger = LoggerFactory.getLogger(FirstPageController.class);
	@Autowired
	private CustomersService customersService;
	@Autowired
	private AreaGroupService areaGroupService;
	@Autowired
	private LogisticsCompanyService logisticsCompanyService;
	@Autowired
	private OrderExportService orderExportService;
	/**
	 * 导向超区件管理页面
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "show")
	public String toFirstPage(Model model, ServletRequest request) {

		// 查出当前用户关联的商家列表
		ShiroUser curUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
		List<Customers> customerList = customersService.loadCustomerByAuthority(curUser);
		model.addAttribute("customerList", customerList);

		model.addAttribute("logisticsList", logisticsCompanyService.findAll());

		List<AreaGroup> warehouseList = areaGroupService.findByAreaGroups(curUser.areagroups);
		model.addAttribute("warehouseList", warehouseList);

		return "orderexport/orderExport";
	}
	
	@RequestMapping(value = "queryOrder")
	public void queryOrder(@RequestBody JSONParam[] paramJson, HttpServletRequest request,HttpServletResponse response) {
		try {
			PrintWriter out=response.getWriter();
			JSONObject json=new JSONObject();
			// 客户端参数
			Map<String, String> paramMap = DataTablesUtils.convertToMap(paramJson);
			Map<String, Object> param=new HashMap<String, Object>();

			ShiroUser shiroUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();

			String sEcho = paramMap.get("sEcho");  
			int start = Integer.parseInt(paramMap.get("iDisplayStart"));
			int length = Integer.parseInt(paramMap.get("iDisplayLength")); 
            String customerCode = paramMap.get("customerCode");
            String warehouseCode = paramMap.get("warehouseCode");
            String orderno = paramMap.get("orderno");
            String status = paramMap.get("status");
            String dataRange = paramMap.get("dataRange");
			String logistics = paramMap.get("logistics");
			String mailNo = paramMap.get("mailNo");
			String batchCode = paramMap.get("batchCode");
			String taskCode = paramMap.get("taskCode");
			
			//封装查询参数
			if(StringUtils.isEmpty(customerCode)){ //如果商家编码为空，赋予默认权限值
				String customerCodes=this.customersService.loadCustomerByAuthority(shiroUser.jobuuid);
				param.put("customerCodes", customerCodes);
			}else{
				param.put("customerCode", customerCode);
			}
			param.put("warehouseCode", warehouseCode);
			if(StringUtils.isNotBlank(orderno)){ 
				param.put("orderno", orderno);
			}
			if(StringUtils.isNotBlank(status)){ 
				param.put("status", status);
			}
			Map<String, Date> dataMap=DateUtils.getDateRange(dataRange);
            Date fromDate=dataMap.get("fromDate");
            Date toDate=dataMap.get("toDate");
            param.put("fromDate", fromDate);
            param.put("toDate", toDate);
            if(StringUtils.isNotBlank(logistics)){ 
				param.put("expressCompany", logistics);
			}
            if(StringUtils.isNotBlank(mailNo)){ 
				param.put("mailNo", mailNo);
			}
            if(StringUtils.isNotBlank(batchCode)){ 
				param.put("batchCode", batchCode);
			}
            if(StringUtils.isNotBlank(taskCode)){ 
				param.put("taskCode", taskCode);
			}       
        	param.put("cancelStatus", "ok");
        	//查询
			int curPage=(start/length)+1;
			Page<WorkOrder>  page = orderExportService.loadPageOrder(param,curPage, length);
	        List<WorkOrder> orderList=page.getContent();
	        
	        //封装查询结果
	        json.put("aaData", orderList);
	        json.put("sEcho", sEcho);
	        json.put("iTotalRecords", page.getTotalElements());
	        json.put("iTotalDisplayRecords", page.getTotalElements());
	        
	        out.print(json.toString());
		} catch (Exception e) {
			log.error("error",e);
		}
	}
	
	/**
	 * 导出excel
	 * 
	 *
	 * @param model
	 * @param request
	 * @param response
	 * @return [参数说明]
	 * @author <a href=mailto:zhangweize@nryuncang.com>zhangweize</a>
	 * @version 1.0.0
	 */
	@RequestMapping(value = "exportExcel")
	public String exportExcel(Model model, ServletRequest request,ServletResponse response){
		FileInputStream f=null;
		OutputStream output=null;
		try {
			Date now=new Date();
			DateFormat df=new SimpleDateFormat("yyyyMMddhhmmss");
			
			// 查询商品
			Map<String, Object> param = Servlets.getParametersStartingWith(request, "_");
			String customerCode = (String) param.get("customerCode");
			String warehouseCode = (String) param.get("warehouseCode");
			String dataRange = (String) param.get("dataRange") ; 
			Map<String, Date> dataMap=DateUtils.getDateRange(dataRange);
            Date fromDate=dataMap.get("fromDate");
            Date toDate=dataMap.get("toDate");
            param.put("fromDate", fromDate);
            param.put("toDate", toDate);
            
			List<EdiOrder> orderList = orderExportService.exportOrderList(param);
			//** 定义导出数据集合 *//
			List<Object[]> list = new ArrayList<Object[]>();
			SimpleDateFormat formatter=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			
	        int queryNum = orderList.size() / 10 + (orderList.size() % 10 == 0 ? 0 : 1);
			
			for (int i = 0; i < queryNum; i++) {
				try {
					List<EdiOrder> subOrderList = orderList.subList(i*10 , orderList.size() < (i+1)*10 ? orderList.size() : (i+1)*10);
					List<EdiOrder> countEdiOrderSkuList = orderExportService.exportOrderItemNum(subOrderList);

					for (EdiOrder orders : subOrderList) {
						for (EdiOrder ediOrderSku : countEdiOrderSkuList) {
							if (StringUtils.equals(orders.getOrdeno(), ediOrderSku.getOrdeno())) {
								Object[] obj = { 
										orders.getOrdeno(),
										orders.getSendCompany(), 
										orders.getSendna(),
										orders.getSendMobile(), 
										orders.getSendAddress(),
										orders.getReceCompany(),
										orders.getRecena(), 
										orders.getTeleph(), 
										orders.getMobile(),
										orders.getAddres(),
										null, 
										null, 
										ediOrderSku.getSku(), 
										ediOrderSku.getSkuTypeNum(),
										1, 
										null, 
										null, 
										null, 
										orders.getBatchCode(),
										orders.getBackupTaskCode(), 
										orders.getRankno(), 
										null 
									};
								list.add(obj);
							}

						}
					}

				} catch (Exception e) {

					logger.error("error", e);
				}
			}
			
			//** 导出数据 *//
			String[] title = { "用户订单号", "寄件公司", "联系人", "联系电话", "寄件地址", "收件公司", "联系人", "联系电话", "手机号码", "收件详细地址", "付款方式",
					"第三方付月结卡号", "托寄物内容", "托寄物数量", "件数", "实际重量（KG）", "计费重量（KG）", "业务类型", "作业批次号", "作业任务号", "任务序号" };
			String filepath = customerCode+"_"+warehouseCode+"_Order.xls";
			//String title_page=customers.getCustomerName()+"缺货订单表";
			ExcelUtils.writeExcel(title, filepath, df.format(now) , list); // 生成excel
			//** 把生成的excel文件读出字节返回给客户端 *//
			((HttpServletResponse)response).setHeader("Content-disposition", "attachment; filename="+ new String(filepath.getBytes("gb2312"),"utf-8"));
			f = new FileInputStream(ExcelUtils.TEMPPATH+filepath);
			byte[] fb = new byte[f.available()];
			f.read(fb);
			ByteArrayInputStream bais = new ByteArrayInputStream(fb);
			output =((HttpServletResponse)response).getOutputStream();
			int by = 0;
			while ((by = bais.read()) != -1) {
				output.write(by);
			}
			output.flush();
			
		} catch (Exception e) {
			return "error";
		}finally{
			if (output!=null) {
				try { output.close(); } catch (IOException e) {logger.error("error",e);}
			}
			if (f!=null) {
				try { f.close(); } catch (IOException e)  {logger.error("error",e);}
			}
		}
		return null;
	}
	
	
}
